angular.module('checkGoods.services')

.factory('UsbPortService', ['$rootScope', '$timeout',
	function($rootScope, $timeout) {
	    var o = {},
            _notify = false,
            _inputCache = '',
            _timeOut;

        // 开始监听U口输入    
        o.start = function () {
            if (_notify) {
                return;
            }
            _notify = true;
            _inputCache = '';
            angular.element(document).keypress(onKeyPress);
        };
        // 停止监听U口输入
        o.stop = function () {
            if (!_notify) {
                return;
            }
            _notify = false;
            _inputCache = '';
            angular.element(document).off('keypress', onKeyPress);
        };

        return o;

        function onKeyPress (event) {
            if (_timeOut) {
                $timeout.cancel(_timeOut);
            }
            if (event.keyCode === 13) {
                if (_inputCache.length > 0) {
                    $rootScope.$broadcast('UsbPortService.input', _inputCache);
                    _inputCache = '';
                }
                return;
            }
            _inputCache += String.fromCharCode(event.keyCode);
            // 两次读入间隔小于50ms认为是U口输入，否则为人工输入，清空输入缓存
            _timeOut = $timeout(function () {
                _inputCache = '';
            }, 50);
        }
	}
]);
